package fun.codedesign.jdk.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CycliBarrier {

    public static void main(String[] args) {

        CyclicBarrier c = new CyclicBarrier(2, new Runnable() {

            // 由最后一个到达的参与者唤醒其他线程并且调用本方法
            @Override
            public void run() {
                System.out.println("隧道打通");

            }
        });

        new Thread(new WaTask(c), "工人1").start();
        new Thread(new WaTask(c), "工人2").start();

    }
}

class WaTask implements Runnable {
    private CyclicBarrier c;

    public WaTask(CyclicBarrier c) {
        this.c = c;
    }

    @Override
    public void run() {
        System.out.println("挖隧道中");
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            c.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
